﻿using System.IO;
using System.Text;

namespace Unikado.PHPLibs.Tokenizer
{

    /// <summary>
    /// This class let you extract all tokens of a PHP file of from a PHP code string.
    /// </summary>
    public static class PhpTokenizer
    {

        #region - - - - - -   P U B L I C   M E T H O D S   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        /// <summary>
        /// Parse the current defined file with the defined encoding.
        /// </summary>
        /// <param name="phpFile">The PHP file to parse</param>
        /// <param name="enc">The encoding of the PHP file (Fallback is UTF-8)</param>
        /// <returns>All Tokens of the defined File</returns>
        public static TokenCollection ParseFile(string phpFile, Encoding enc = null)
        {
            TokenCollection result;
            using (var fs = new FileStream(phpFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var parser = new PhpCodeStreamParser();
                result = parser.Parse(fs, enc ?? new UTF8Encoding(false));
            }
            return result;
        }
        /// <summary>
        /// Parse the current defined PHP code string.
        /// </summary>
        /// <param name="phpCode">The PHP code to parse.</param>
        /// <param name="enc">Encoding</param>
        /// <returns>All Tokens of the defined PHP code</returns>
        public static TokenCollection ParseString(string phpCode, Encoding enc = null)
        {
            if (enc == null) enc = new UTF8Encoding(false);
            TokenCollection result;
            using (var ms = new MemoryStream(enc.GetBytes(phpCode)))
            {
                ms.Position = 0;
                var parser = new PhpCodeStreamParser();
                result = parser.Parse(ms, enc);
            }
            return result;
        }

        #endregion

    }

}